package org.example.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.util.HashMap;

public class WorkQueueProducerTest {

    private static final String QUEUE_NAME = "work_queue";

    public static void main(String[] args) throws Exception {

        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2.设置公布过程连接的主机ip
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setConnectionTimeout(10000);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        try (Connection connection = connectionFactory.newConnection()) {
            //3.获取channel对象
            Channel channel = connection.createChannel();
            channel.basicQos(1);
            //4.声明一个队列
            // To send, we must declare a queue for us to send to; then we can publish a message to the queue,
            // all of this in the try-with-resources statement:
            /**Scanner scanner = new Scanner(System.in);
             while (scanner.hasNext()) {
             String line = scanner.next();
             channel.queueDeclare(QUEUE_NAME, false, false, false,
             new HashMap<String, Object>());
             //5.发送消息
             if (line.equals("exit")) {
             System.exit(1);
             }
             channel.basicPublish("", QUEUE_NAME, null, line.getBytes());
             System.out.println(" [x] Sent '" + line + "'");
             }**/
            for (int i = 0; i < 10000; i++) {
                //消息持久化
                boolean durable = true;
                channel.queueDeclare(QUEUE_NAME, durable, false, false, new HashMap<>());
                //props=PERSISTENT_TEXT_PLAIN
                channel.basicPublish("", QUEUE_NAME,
                        MessageProperties.PERSISTENT_TEXT_PLAIN, ("消息" + i).getBytes());
                System.out.println("发送消息=" + ("消息" + i));
            }
        } finally {
            //do nothing

        }
    }
}
